#include "budget_edit.h"
#include "ui_budget_edit.h"
#include<QMessageBox>
#include<QDebug>
#include<QDesktopWidget>
#include<QtSql/QSqlQuery>
//This class allow user to assign budget to an account

Budget_edit::Budget_edit(QString label,QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Budget_edit)
{
    ui->setupUi(this);
    account=label;//Account name
    QRect innersize=QApplication::desktop()->availableGeometry(this);
    //ui->listWidget->setGeometry(0,50,(innersize.width()),(innersize.height()));
    ui->scrollArea->setGeometry(0,0,(innersize.width()),(innersize.height()));
    int fontSize=10;
    ui->label_header->setFocus();
    ui->verticalLayout_2->setStretch(0,0);
    ui->verticalLayout_2->setStretch(1,0);
    ui->verticalLayout_2->setStretch(2,5);
    ui->label_header->setFont(QFont("lucida",fontSize,QFont::Normal,false));
    ui->label_new->setFont(QFont("lucida",(fontSize-2),QFont::Normal,false));
    ui->new_budget->setFont(QFont("lucida",(fontSize-2),QFont::Normal,false));
    ui->save_button->setFont(QFont("lucida",(fontSize-2),QFont::Normal,false));
    ui->label_header->setText(ui->label_header->text()+" "+account);
    ui->new_budget->setValidator(new QDoubleValidator(this));
    QAction* backAction = new QAction( tr("Back"), this );
     backAction->setSoftKeyRole( QAction::NegativeSoftKey );
     connect(backAction, SIGNAL(triggered()), this, SLOT(back()));
     addAction( backAction );
     if(db.db_connect())
     {
      QSqlQuery qry;
      qry.prepare(QString("select budget_amt from account_table where name='%1'").arg(account));
      if(qry.exec())
      {
          qry.next();
          double old_budget=qry.value(0).toDouble();
          ui->new_budget->setText(QString("%1").arg(old_budget));
      }
      db.db_close();
      //qDebug()<<"closed";
  }



}

Budget_edit::~Budget_edit()
{
    delete ui;

}
void Budget_edit::back()
{
    (new Budget)->show();
}

void Budget_edit::on_save_button_clicked()
{
    QString s=ui->new_budget->text();
    double new_budget=s.toDouble();
    if((s.compare("")!=0)&&(new_budget>=0))
    {

        if(db.db_connect())
        {
            if(db.budget_update(account,new_budget))
            {
                QMessageBox::information(0,"Success !","Budget modified");
                (new Budget)->show();
            }
            db.db_close();
         }

        }
    else
        QMessageBox::information(0,"Error !","Please enter new budget amount !");

    }

